import { createContext, useContext, useRef, useState } from 'react'
import { createPortal } from 'react-dom'
import { HiEllipsisVertical } from 'react-icons/hi2'
import styled from 'styled-components'

const _StyledMenu = styled.div`
  display: flex;
  align-items: center;
  justify-content: flex-end;
`

const _StyledToggle = styled.button`
  background: none;
  border: none;
  padding: 0.4rem;
  border-radius: var(--border-radius-sm);
  transform: translateX(0.8rem);
  transition: all 0.2s;

  &:hover {
    background-color: var(--color-grey-100);
  }

  & svg {
    width: 2.4rem;
    height: 2.4rem;
    color: var(--color-grey-700);
  }
`

const _StyledList = styled.ul`
  position: fixed;

  background-color: var(--color-grey-0);
  box-shadow: var(--shadow-md);
  border-radius: var(--border-radius-md);

  right: ${(props) => props.position.x}px;
  top: ${(props) => props.position.y}px;
`

const _StyledButton = styled.button`
  width: 100%;
  text-align: left;
  background: none;
  border: none;
  padding: 1.2rem 2.4rem;
  font-size: 1.4rem;
  transition: all 0.2s;

  display: flex;
  align-items: center;
  gap: 1.6rem;

  &:hover {
    background-color: var(--color-grey-50);
  }

  & svg {
    width: 1.6rem;
    height: 1.6rem;
    color: var(--color-grey-400);
    transition: all 0.3s;
  }
`

const MenusContext = createContext()

function Menus({ children }) {
	const [_openId, setOpenId] = useState(null)
	const [_position, _setPosition] = useState({ x: 0, y: 0 })

	const _close = () => setOpenId(null)
	const _open = setOpenId

	return (
		<MenusContext.Provider
			value={{ _close, _open, _openId, _position, _setPosition }}
		>
			{children}
		</MenusContext.Provider>
	)
}

function Menu({ children }) {
	return <_StyledMenu>{children}</_StyledMenu>
}

function Toggle({ id }) {
	const { _close, _open, _openId, _setPosition } = useContext(MenusContext)

	const handleClick = (e) => {
		const rect = e.target.closest('button').getBoundingClientRect()

		_setPosition({
			x: window.innerWidth - rect.width - rect.x,
			y: rect.y + rect.height + 8
		})

		_openId === '' || _openId !== id ? _open(id) : _close()
	}

	return (
		<_StyledToggle>
			<HiEllipsisVertical onClick={handleClick} />
		</_StyledToggle>
	)
}

function List({ children, id }) {
	const { _close, _openId, _position } = useContext(MenusContext)
	const ref = useRef(null)

	if (_openId !== id) return null

	return createPortal(
		<_StyledList position={_position} ref={ref}>
			{children}
		</_StyledList>,
		document.body
	)
}

function Button({ icon, onClick, children }) {
	const { _close } = useContext(MenusContext)

	function handleClick() {
		onClick?.()
		_close()
	}

	return (
		<_StyledButton onClick={handleClick}>
			<span>{icon}</span>
			{children}
		</_StyledButton>
	)
}

Menus.Menu = Menu
Menus.Toggle = Toggle
Menus.List = List
Menus.Button = Button

export default Menus
